import time
from selenium import webdriver
from selenium.common import NoSuchElementException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium_stealth import stealth

main_page = "https://www.okx.com/cn"
eth_usdt = "https://www.okx.com/cn/trade-spot/"


class AutoAction:
    def __init__(self, user_data_dir):
        self.user_data_dir = user_data_dir
        self.browser = self.init_browser()

    def init_browser(self):
        options = webdriver.ChromeOptions()
        options.add_argument(f"user-data-dir={self.user_data_dir}")
        options.add_experimental_option("excludeSwitches", ['enable-automation'])
        options.add_experimental_option("detach", True)
        browser = webdriver.Chrome(options=options)

        stealth(browser,
                languages=["en-US", "en"],
                vendor="Google Inc.",
                platform="Win32",
                webgl_vendor="Intel Inc.",
                renderer="Intel Iris OpenGL Engine",
                fix_hairline=True,
                )
        return browser

    def open_page(self, url):
        self.browser.get(url)
        WebDriverWait(self.browser, 10).until(
            EC.presence_of_element_located((By.ID, "navContainer"))
        )
        print(url + " 打开成功")

    def login_by_google(self):
        WebDriverWait(self.browser, 10).until(
            EC.presence_of_element_located((By.ID, "google-client-button"))
        )
        try:
            # 步骤1: 记录当前打开的窗口句柄
            original_window_handles = set(self.browser.window_handles)

            # 步骤2: 执行操作以触发新窗口打开
            # 尝试查找具有特定 google-client-button 属性的元素
            googleLogin = self.browser.find_element(By.XPATH,
                                                    "//div[@id='google-client-button']/ancestor::button")
            WebDriverWait(self.browser, 10).until(EC.element_to_be_clickable(googleLogin))
            # 等待后台google账号记载完成，否则点击无效
            time.sleep(2)
            googleLogin.click()
            # 等待弹窗打开
            time.sleep(1)
            # 步骤3: 获取所有窗口句柄，并找出新打开的窗口句柄
            new_window_handles = set(self.browser.window_handles)
            new_window_handle = (new_window_handles - original_window_handles).pop()

            # 步骤4: 切换到新窗口
            self.browser.switch_to.window(new_window_handle)
            try:
                # 尝试查找具有特定 aria-labelledby 属性的元素
                WebDriverWait(self.browser, 10).until(
                    EC.presence_of_element_located(
                        (By.XPATH, "//*[@aria-labelledby='picker-item-label-0']"))
                )
                element = self.browser.find_element(By.XPATH, "//*[@aria-labelledby='picker-item-label-0']")
                WebDriverWait(self.browser, 10).until(EC.element_to_be_clickable(element))
                print("找到了具有 'aria-labelledby=\"picker-item-label-0\"' 的元素。")
                element.click()
            except NoSuchElementException:
                # 如果没有找到该元素，打印信息
                print("没有找到具有 'aria-labelledby=\"picker-item-label-0\"' 的元素。")

        except NoSuchElementException:
            # 如果没有找到该元素，打印信息
            print("没有找到具有 'google-client-button' 的元素。")

        print("登录界面加载完成")
        print("登录成功，返回主窗口")
        self.browser.switch_to.default_content()

    def login(self):
        # 判断是否已登录的逻辑
        try:
            # 判断是未登录
            self.browser.find_element(By.CLASS_NAME, "not-login")
            self.login()
        except NoSuchElementException:
            # 如果没有找到指定的类，说明用户可能已经登录
            print("没有找到 'not_login'，用户可能已经登录。")
            return

        try:
            # 尝试查找是否存在指定的类
            login_element = self.browser.find_element(By.CLASS_NAME, "user-login-btn")
            # 如果找到了，执行点击操作
            print("找到 'user-no-login'，现在点击 '登录' 按钮。")
            login_element.click()
            self.login_by_google()
        except NoSuchElementException:
            # 如果没有找到指定的类，说明用户可能已经登录
            print("没有找到 'user-no-login'，用户可能已经登录。")

    def buy(self, num):
        print("进入购买程序")
        WebDriverWait(self.browser, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, "place-order-inner-common"))
        )
        time.sleep(1)
        tabs_container = self.browser.find_element(By.CLASS_NAME, "place-order-inner-common")
        market_order_tab = tabs_container.find_element(By.XPATH, ".//div[contains(text(), '市价委托')]")
        market_order_tab.click()
        leftPoForm_element = self.browser.find_element(By.ID, "leftPoForm")
        input_element = leftPoForm_element.find_element(By.XPATH, ".//input[@name='total']")
        print("执行购买" + num)
        ActionChains(self.browser).double_click(input_element).perform()
        input_element.send_keys(num)
        submit_button = leftPoForm_element.find_element(By.CLASS_NAME, "submit-btn")
        submit_button.click()
        time.sleep(1)
        confirm_dialog = self.browser.find_element(By.CLASS_NAME, "okui-dialog-window-float")
        if confirm_dialog:
            confirm_element = confirm_dialog.find_element(By.CLASS_NAME, "submit-confirm-box")
            if confirm_element:
                confirm_dialog.find_element(By.CLASS_NAME, "btn-fill-highlight").click()
    def sell(self, num):
        print("进入售卖程序")
        WebDriverWait(self.browser, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, "place-order-inner-common"))
        )
        time.sleep(1)
        tabs_container = self.browser.find_element(By.CLASS_NAME, "place-order-inner-common")
        market_order_tab = tabs_container.find_element(By.XPATH, ".//div[contains(text(), '市价委托')]")
        market_order_tab.click()
        rightPoForm_element = self.browser.find_element(By.ID, "rightPoForm")
        input_element = rightPoForm_element.find_element(By.XPATH, ".//input[@name='size']")
        print("执行售卖" + num)
        ActionChains(self.browser).double_click(input_element).perform()
        input_element.send_keys(num)
        submit_button = rightPoForm_element.find_element(By.CLASS_NAME, "submit-btn")
        submit_button.click()
        time.sleep(1)
        confirm_dialog = self.browser.find_element(By.CLASS_NAME, "okui-dialog-window-float")
        if confirm_dialog:
            confirm_element = confirm_dialog.find_element(By.CLASS_NAME, "submit-confirm-box")
            if confirm_element:
                confirm_dialog.find_element(By.CLASS_NAME, "btn-fill-highlight").click()
    def close_browser(self):
        self.browser.quit()
        print("浏览器已关闭。")


if __name__ == '__main__':
    user_data_dir = "C:\\Users\\Administrator\\PycharmProjects\\authokxtool\\UD2"
    auto_action = AutoAction(user_data_dir)
    auto_action.open_page(main_page)
    auto_action.login()
    auto_action.open_page(eth_usdt)
    # auto_action.buy(1)
    # auto_action.sell(1)
    time.sleep(1000)
